const express = require('express');
const  router = express.Router();

// 添加用户
router.post('/add' ,async (req,res)=>{
    const { User }  = req.Model;
    
    let {
        user,  
        password, 
        time,

    }  = req.body;
    let userId = req.headers.authorization

    const params = {}
    params.user = user
    params.userId = userId
     // 数据过滤的操作 

    let users = await User.findOne(params) 
    if(users) {
        return  res.send({code:500,info:'用户已存在!'})
    }else {
        try {
            await User.create({
                user,    
                password,        
                time, 
                userId
            })
            res.send({code:200,info:'添加成功'})
        } catch(e) {
        //    console.log('eeee',e)
            res.send({code:500,info:'添加失败'})
        }
    }
})

//修改商品
router.post('/edit' ,async (req,res)=>{
    const { User }  = req.Model;
       // 数据过滤的操作 
    const { Userid ,...updateData} = req.body;
    try {
        await User.findByIdAndUpdate(Userid,updateData);
        res.send({code:200,info:'修改成功'})
    } catch(e) {
        res.send({code:500,info:'修改失败'})
    }
  
})

// 分页查询
router.post('/getAll', async (req,res)=>{

    const { User} = req.Model;
    let { current=1,limit=10,value } = req.body;
    let userId = req.headers.authorization
    const skip =  (current - 1 ) * limit; // 查询的起点（偏移量）
    const params = {}
    params.userId = userId
    if(value) params.user = new RegExp(value, 'i');
    try {

       let users = await User.find(params,{},{skip,limit}) // 分页查询
       let num = await User.find(params,{},{})
       let count = num.length
    //    let count = await User.count() // 获取符合条件的总数

       res.send({code:200,info:'查询成功',data:users,count});
       
    }catch(e){
       res.send({code:500,info:'获取失败'})
    }

})

// 查询单个商品信息
router.post('/getOne', async (req,res)=>{
    const { User} = req.Model;
  
    let { Userid } = req.body;
  
    if(!Userid) return res.send({code:500,info:'该用户不存在'})
  
    try {
  
      let users = await User.findById(Userid) // 分页查询
     
      res.send({code:200,info:'查询成功',data:users});
      
    }catch(e){
      res.send({code:500,info:'获取失败'})
    }
  })

router.post('/del', async (req,res)=>{
    const { User } = req.Model;
    let { Userid } = req.body;
  
    if(!Userid) return res.send({code:500,info:'该用户不存在'})
  
    try {
      await User.findByIdAndRemove(Userid) 
     
      res.send({code:200,info:'删除成功'});
      
    }catch(e){
  
      res.send({code:500,info:'删除失败'})
    }
})
module.exports = router;
